/*
 * @(#)User.java
 * 2011-5-9 下午08:56:18
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.accountmng.entity;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OrderBy;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.google.common.collect.Lists;
import com.qyxx.platform.common.module.entity.BaseEntity;
import com.qyxx.platform.common.utils.reflection.ConvertUtils;

/**
 * 用户
 * 
 * @author gxj
 * @version 1.0
 * @since 1.6 2011-5-9 下午08:56:18
 */
@Entity
// 表名与类名不相同时重新定义表名.
@Table(name = "SYS_USER")
// 默认的缓存策略.
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
@JsonIgnoreProperties({ "hibernateLazyInitializer", "handler" })
public class User extends BaseEntity implements Serializable {

	private static final long serialVersionUID = 2624553984427192476L;
	
	private Long id;
	private String loginName;
	private String password;// 为简化演示使用明文保存的密码
	private String realName;
	private Organization organization;///---
	private String organizationName;//---
	private String organizationId;
	private User user;//----
	private String managerName;//---
	private String managerId;
	private String remoteLogin;
	private String sex;
	private String mobilePhone;
	private String fax;
	private String email;
	private String address;
	private String status;
	private Long allowerror;
	private Long alledyerror;//同时在线登录数
	private String remark;
	private String isSuperAdmin;
	private String employeeId;
	private String nickname;
	private String statusView;//---
	private String roleName;
	private List<Role> roleList = Lists.newArrayList();// 有序的关联对象集合
	
	private List<String> dataAuthList = Lists.newArrayList(); //数据权限标识url集合
	
	private String orgCode;
	private String indexUrl;//首页地址
	private String portalUrl;//门户地址
	
	private List<Role> seeRoleList = Lists.newArrayList();//可见用户角色集合
	
	private Map<String, Map<String,List<Long>>> seeUserIdMap = new HashMap<String, Map<String,List<Long>>>();//可见用户ID集合
	
	private Map<String, List<String>> fieldCondMap = new HashMap<String, List<String>>();//字段条件权限
	
	private String bindIp;//绑定IP地址
	
	private String avatar;//头像地址
	
	private String signature;//个性签名

	private String uid;//对应IM中ID

	@Id
	@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_SYS_USER_ID")
	@SequenceGenerator(name = "SEQ_SYS_USER_ID", sequenceName = "SEQ_SYS_USER_ID")
	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	// 字段非空且唯一, 用于提醒Entity使用者及生成DDL.
	@Column(nullable = false, unique = true)
	public String getLoginName() {
		return loginName;
	}

	public void setLoginName(String loginName) {
		this.loginName = loginName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public void setRealName(String realName) {
		this.realName = realName;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@ManyToOne
	@JoinColumn(name = "ORGANIZATION_ID")
	@JsonIgnore
	public Organization getOrganization() {
		return organization;
	}

	public void setOrganization(Organization organization) {
		this.organization = organization;
	}

	@Transient
	public String getOrganizationName() {
		if (this.getOrganization() != null) {
			return this.getOrganization().getOrganizationName();
		} else {
			return organizationName;
		}
	}

	public void setOrganizationName(String organizationName) {
		this.organizationName = organizationName;
	}

	
	/**
	 * @return organizationId
	 */
	@Transient
	public String getOrganizationId() {
		if (this.getOrganization() != null) {
			return this.getOrganization().getId().toString();
		} else {
			return organizationId;
		}
		
	}

	
	/**
	 * @param organizationId
	 */
	public void setOrganizationId(String organizationId) {
		this.organizationId = organizationId;
	}

	
	/**
	 * @return managerId
	 */
	@Transient
	public String getManagerId() {
		if (this.getUser() != null) {
			return this.getUser().getId().toString();
		} else {
			return managerId;
		}
		
	}

	
	/**
	 * @param managerId
	 */
	public void setManagerId(String managerId) {
		this.managerId = managerId;
	}

	// 多对多定义
	@ManyToMany
	// 中间表定义,表名采用默认命名规则
	@JoinTable(name = "SYS_USER_TO_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
	// Fecth策略定义
	@Fetch(FetchMode.SUBSELECT)
	// 集合按id排序.
	@OrderBy("id")
	// 集合中对象id的缓存.
	//@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	@JsonIgnore
	public List<Role> getRoleList() {
		return roleList;
	}

	public void setRoleList(List<Role> roleList) {
		this.roleList = roleList;
	}


	/**
	 * @return seeRoleList
	 */
	//多对多定义
	@ManyToMany
	// 中间表定义,表名采用默认命名规则
	@JoinTable(name = "SYS_ROLE_SEE_USER", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
	// Fecth策略定义
	@Fetch(FetchMode.SUBSELECT)
	// 集合按id排序.
	@OrderBy("id")
	// 集合中对象id的缓存.
	@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
	@JsonIgnore
	public List<Role> getSeeRoleList() {
		return seeRoleList;
	}

	
	/**
	 * @param seeRoleList
	 */
	public void setSeeRoleList(List<Role> seeRoleList) {
		this.seeRoleList = seeRoleList;
	}

	/**
	 * @return bindIp
	 */
	@Column(name="BIND_IP",length=100)
	public String getBindIp() {
		return bindIp;
	}

	
	/**
	 * @param bindIp
	 */
	public void setBindIp(String bindIp) {
		this.bindIp = bindIp;
	}

	/**
	 * 用户拥有的角色名称字符串, 多个角色名称用','分隔.
	 */
	// 非持久化属性.
	@Transient
	//@JsonIgnore
	public String getRoleNames() {
		return ConvertUtils.convertElementPropertyToString(roleList,
				"roleName", ",");
	}

	/**
	 * 用户拥有的角色id字符串, 多个角色id用','分隔.
	 */
	// 非持久化属性.
	@Transient
	@SuppressWarnings("unchecked")
	//@JsonIgnore
	public List<Long> getRoleIds() {
		return ConvertUtils.convertElementPropertyToList(roleList,
				"id");
	}


	@ManyToOne
	@JoinColumn(name = "MANAGER_ID")
	@JsonIgnore
	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	@Transient
	public String getManagerName() {
		if (this.getUser() != null) {
			return this.getUser().getRealName();
		} else {
			return managerName;
		}

	}

	public void setManagerName(String managerName) {
		this.managerName = managerName;
	}

	public String getRemoteLogin() {
		return remoteLogin;
	}

	public void setRemoteLogin(String remoteLogin) {
		this.remoteLogin = remoteLogin;
	}

	public String getSex() {

		return sex;

	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public String getMobilePhone() {
		return mobilePhone;
	}

	public void setMobilePhone(String mobilePhone) {
		this.mobilePhone = mobilePhone;
	}

	public String getFax() {
		return fax;
	}

	public void setFax(String fax) {
		this.fax = fax;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}
	//@JsonIgnore
	public String getStatus() {
		
		return status;
	
		

	}

	public void setStatus(String status) {
		this.status = status;
	}

	
	/**
	 * @return statusView
	 */
	@Transient
	//@JsonProperty(value="status")
	public String getStatusView() {
		return statusView;
	}

	
	/**
	 * @param statusView
	 */
	public void setStatusView(String statusView) {
		this.statusView = statusView;
	}

	/**
	 * @return allowerror
	 */
	public Long getAllowerror() {
		return allowerror;
	}

	
	/**
	 * @param allowerror
	 */
	public void setAllowerror(Long allowerror) {
		this.allowerror = allowerror;
	}

	
	/**
	 * @return alledyerror
	 */
	public Long getAlledyerror() {
		return alledyerror;
	}

	
	/**
	 * @param alledyerror
	 */
	public void setAlledyerror(Long alledyerror) {
		this.alledyerror = alledyerror;
	}

	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}

	public String getIsSuperAdmin() {
		return isSuperAdmin;
	}

	public void setIsSuperAdmin(String isSuperAdmin) {
		this.isSuperAdmin = isSuperAdmin;
	}

	public String getEmployeeId() {
		return employeeId;
	}

	public void setEmployeeId(String employeeId) {
		this.employeeId = employeeId;
	}

	public String getNickname() {
		return nickname;
	}

	public void setNickname(String nickname) {
		this.nickname = nickname;
	}

	public String getRealName() {
		return realName;
	}

	@Transient
	public String getRoleName() {
		return roleName;
	}

	
	public void setRoleName(String roleName) {
		this.roleName = roleName;
	}

	
	/**
	 * @return dataAuthList
	 */
	@Transient
	public List<String> getDataAuthList() {
		return dataAuthList;
	}

	
	/**
	 * @param dataAuthList
	 */
	public void setDataAuthList(List<String> dataAuthList) {
		this.dataAuthList = dataAuthList;
	}

	
	/**
	 * @return orgCode
	 */
	@Transient
	public String getOrgCode() {
		return orgCode;
	}

	
	/**
	 * @param orgCode
	 */
	public void setOrgCode(String orgCode) {
		this.orgCode = orgCode;
	}
	
	
	/**
	 * @return indexUrl
	 */
	@Transient
	public String getIndexUrl() {
		return indexUrl;
	}

	
	/**
	 * @param indexUrl
	 */
	public void setIndexUrl(String indexUrl) {
		this.indexUrl = indexUrl;
	}

	
	/**
	 * @return portalUrl
	 */
	@Transient
	public String getPortalUrl() {
		return portalUrl;
	}

	
	/**
	 * @param portalUrl
	 */
	public void setPortalUrl(String portalUrl) {
		this.portalUrl = portalUrl;
	}

	/** 
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("User [id=");
		builder.append(id);
		builder.append(", loginName=");
		builder.append(loginName);
		builder.append("]");
		return builder.toString();
	}
	@Transient
	public Boolean isHaveRole(String roleName) {
		List<Role> rList = this.roleList;
		if (rList != null) {
			for (Role r : rList) {
				String rn = r.getRoleName();
				if (rn.equals(roleName)) {
					return true;
				}
			}
		}
		return false;
	}
	@Transient
	public Boolean isLoginName(String loginName) {
		String []  lns = StringUtils.split(loginName,",");
		Boolean flag = false;
		for(String lg :lns ){
			if(this.loginName.equals(lg)){
				flag = true;
				break;
			}
		}
		return flag ;
	}

	
	/**
	 * 根据模块KEY获取可见用户列表
	 * 
	 * @param moduleKey
	 * @return
	 */
	@Transient
	public Map<String,List<Long>> getSeeUserIdList(String moduleKey) {
		String resKey = "RES_" + moduleKey.toUpperCase()+ "_SEL_USER_VISIBLE";
		return seeUserIdMap.get(resKey);
	}

	
	/**
	 * @param seeUserIdMap
	 */
	public void setSeeUserIdMap(Map<String, Map<String,List<Long>>> seeUserIdMap) {
		this.seeUserIdMap = seeUserIdMap;
	}

	
	/**
	 * @param fieldCondMap
	 */
	public void setFieldCondMap(Map<String, List<String>> fieldCondMap) {
		this.fieldCondMap = fieldCondMap;
	}

    
	/**
	 * 根据模块KEY获取字段条件可见权限
	 * 
	 * @param moduleKey
	 * @return
	 */
	@Transient
	public List<String> getFieldCondList(String moduleKey) {
		String resKey = "RES_" + moduleKey.toUpperCase()+ "_FIELD_COND_VISIBLE";
		return fieldCondMap.get(resKey);
	}
	
	/**
	 * @return avatar
	 */
	@Column(name="AVATAR",length=1000)
	public String getAvatar() {
		return avatar;
	}

	
	/**
	 * @param avatar
	 */
	public void setAvatar(String avatar) {
		this.avatar = avatar;
	}

	
	/**
	 * @return signature
	 */
	@Column(name="SIGNATURE",length=200)
	public String getSignature() {
		return signature;
	}

	
	/**
	 * @param signature
	 */
	public void setSignature(String signature) {
		this.signature = signature;
	}

	
	/**
	 * @return uid
	 */
	@Column(name="UID",length=100)
	public String getUid() {
		return uid;
	}

	
	/**
	 * @param uid
	 */
	public void setUid(String uid) {
		this.uid = uid;
	}
}